package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.UserConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.ParamErrorException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.utils.PageUtils;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SetMealDishMapper setMealDishMapper;

    /**
     * 新增菜品与对应的口味
     *  新增菜品时需要设置主键回显, 给每个口味设置菜品id
     *
     * @param dishDTO 需要新增的菜品数据
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        // 插入菜品数据 todo 菜品插入业务是否需要分离出来
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        // 通过主键回显拿到刚刚插入的菜品的id
        Long dishId = dish.getId();
        // 给每个口味设置菜品id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(flavor -> flavor.setDishId(dishId));

        // 插入口味数据
        saveFlavor(flavors);
    }

    /**
     * 分页条件查询菜品信息
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult<DishVO> page(DishPageQueryDTO dishPageQueryDTO) {
        // 校验分页参数
        int page = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();
        PageUtils.validatePageParams(page, pageSize);

        // 开始分页
        PageHelper.startPage(page, pageSize);
        Dish dishDb = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dishDb);

        // 查询数据库
        Page<Dish> dishList = dishMapper.conditionalQuery(dishDb);

        // 封装为Vo返回
        List<DishVO> dishVOList = new ArrayList<>();
        dishList.forEach(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVOList.add(dishVO);
        });

        // 填充分类名称
        dishVOList.forEach(dishVO -> {
            Category category = categoryMapper.getCategoryById(dishVO.getCategoryId());
            dishVO.setCategoryName(category.getName());
        });

        return new PageResult<>(dishList.getTotal(), dishVOList);
    }

    /**
     * 根据分类id查询菜品列表
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getDishListByCategoryId(Long categoryId) {
        Dish dish = new Dish().builder().categoryId(categoryId).build();
        return dishMapper.conditionalQuery(dish);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getDishListById(Long id) {
        Dish dish = dishMapper.getById(id);
        if (Objects.isNull(dish)) {
            return null;
        }
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(dish.getId());
        if (!flavors.isEmpty()) {
            dishVO.setFlavors(flavors);
        }
        return dishVO;
    }

    /**
     * 修改菜品状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        // 校验参数
        if (!UserConstant.validateStatusLegal(status)) {
            throw new ParamErrorException("状态参数不合法");
        }

        Dish dish = new Dish().builder().id(id).status(status).build();
        dishMapper.update(dish);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        // todo 参数校验

        // 修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        // 删除菜品原有口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        // 插入新的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        saveFlavor(dishDTO.getId(), flavors);
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        /**
         * 验证需要删除的菜品是否被套餐引用
         * todo 另一种方案: 根据id列表直接查询套餐中是否包含这些菜品，如果包含则抛出异常
         */
        ids.forEach(id -> {
            List<SetmealDish> setmealDishList = setMealDishMapper.getByDishId(id);
            if (!setmealDishList.isEmpty()) {
                Dish dish = dishMapper.getById(id);
                String message = "菜品[ " + dish.getName() + " ]被套餐引用，无法删除";
                throw new DeletionNotAllowedException(message);
            }
        });

        // 验证需要删除的菜品是否已经禁用
        ids.forEach(id -> {
            Dish dish = dishMapper.getById(id);
            if (UserConstant.STATUS_ENABLE.equals(dish.getStatus())) {
               String message = "菜品[ " + dish.getName() + " ]为启售状态，无法删除";
               throw new DeletionNotAllowedException(message);
           }
        });

        // todo 以上两段逻辑是否可以合并或者抽取出来

        // 删除菜品
        dishMapper.deleteBatch(ids);

        // 删除菜品对应的口味数据
        dishFlavorMapper.deleteBatchByDishIds(ids);
    }

    /**
     * 保存菜品口味
     * @param dishId 菜品id
     * @param flavors 口味数据
     */
    private void saveFlavor(Long dishId, List<DishFlavor> flavors) {
        if (!flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            saveFlavor(flavors);
        }
    }

    /**
     * 保存菜品口味
     * @param flavors 口味数据
     */
    private void saveFlavor(List<DishFlavor> flavors) {
        flavors.forEach(flavor -> {
            if (flavor.getDishId() == null) {
                throw new ParamErrorException("菜品id不能为空");
            }
        });
        if (!flavors.isEmpty()) {
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 将id字符串转化为id列表
     * @param ids id字符串
     * @param separator 分隔符
     * @return
     */
    @Override
    public List<Long> getIdsByString(String ids, String separator) {
        List<Long> idList = new ArrayList<>();
        String[] split = ids.split(separator);
        for (String s : split) {
            idList.add(Long.parseLong(s));
        }
        return idList;
    }
}
